package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.tan.model.domain.ErrorResult;
import com.tan.model.domain.Question;
import com.tan.model.domain.UserInfo;
import com.tan.model.dto.RecommendUserDto;
import com.tan.model.mongo.RecommendUser;
import com.tan.model.mongo.UserLocation;
import com.tan.model.vo.NearUserVo;
import com.tan.model.vo.PageResult;
import com.tan.model.vo.TodayBest;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.*;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.Userthread;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class TanhuaService {
    @DubboReference
    private RecommendUserApi recommendUserApi;
    @DubboReference
    private UserInfoapi userInfoApi;
    @DubboReference
    private QuestionApi questionApi;
    @DubboReference
    private LikeUserapi likeUserApi;
    @DubboReference
    private UserLocationApi userLocationApi;
    @DubboReference
    VisitorsApi visitorsApi;
    @Autowired
    private HuanXinTemplate huanXinTemplate;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @DubboReference
    FriendApi friendApi;
    @Value("${tanhua.default.recommend.users}")
    private String recommendUserId;

    public TodayBest queryWithtodaybest(Long id) {
        return recommendUserApi.queryWithtodaybest(id);
    }

    public PageResult recommendation(RecommendUserDto dto) {
        //1、获取用户id
        Long userId = Userthread.getUser().getId();
        //2、调用recommendUserApi分页查询数据列表（PageResult -- RecommendUser）
        PageResult pr = recommendUserApi.queryRecommendUserList(dto.getPage(),dto.getPagesize(),userId);
        //3、获取分页中的RecommendUser数据列表
        List<RecommendUser> items = (List<RecommendUser>) pr.getItems();
        //4、判断列表是否为空
        if(items == null) {
            return pr;
        }
        //5、提取所有推荐的用户id列表
        List<Long> ids = CollUtil.getFieldValues(items, "userId", Long.class);
        UserInfo userInfo = new UserInfo();
        userInfo.setAge(dto.getAge());
        userInfo.setGender(dto.getGender());
        //6、构建查询条件，批量查询所有的用户详情
        Map<Long, UserInfo> map = userInfoApi.findByIds(ids, userInfo);
        //7、循环推荐的数据列表，构建vo对象
        List<TodayBest> list = new ArrayList<>();
        for (RecommendUser item : items) {
            UserInfo info = map.get(item.getUserId());
            if(info!=null) {
                TodayBest vo = TodayBest.init(info, item);
                list.add(vo);
            }
        }
        //8、构造返回值
        pr.setItems(list);
        return pr;
    }

    public TodayBest queryWithmyliketodaybest(Long id) {
        UserInfo userInfo = userInfoApi.getUserInfo(id);
      Long userId =  Userthread.getUser().getId();
        RecommendUser recommendUser = recommendUserApi.querythisUser(id,userId);
        //构造访客数据调用api保存
        String from="首页";
        String date=new SimpleDateFormat("yyyyMMdd").format(new Date());
       visitorsApi.saveVisitor(userId,id,from,date);
        return TodayBest.init(userInfo, recommendUser);
    }

    public String getStrangerQuestions(Long userId) {
       Question question = questionApi.findByUserId(userId);
       if(question!=null){
           return question.getTxt();
       }
        return "你喜欢我吗";
    }

    public void answerStrangerQuestions(Integer userId, String reply) {


        Long currentUserId = Userthread.getUser().getId();
        UserInfo userInfo = userInfoApi.getUserInfo(currentUserId);
        Long toUserId = Long.valueOf(userId);


     Map map=new HashMap();
     map.put("userId",currentUserId);
     map.put("huanXinId", Constants.HX_USER_PREFIX+currentUserId);
     map.put("nickname",userInfo.getNickname());
     map.put("strangerQuestion",getStrangerQuestions(toUserId));
     map.put("reply",reply);
    String message =  JSON.toJSONString(map);
    Boolean sendMsg =  huanXinTemplate.sendMsg(Constants.HX_USER_PREFIX+toUserId,message);
    if(!sendMsg){
        throw new BusinessException(ErrorResult.error());
    }



    }

    public List<TodayBest> queryCardsList() {
       Long id= Userthread.getUser().getId();
       // 1、调用api查询数据(排除喜欢和不喜欢，数量限制)
        List<RecommendUser> recommendUsers = recommendUserApi.queryCardsList(id,10);
        List<TodayBest> list = new ArrayList<>();
        if (CollUtil.isEmpty(recommendUsers)){
        String[] ids = recommendUserId.split(",");
         for (String pid : ids) {
             RecommendUser recommendUser = new RecommendUser();
             recommendUser.setUserId(Convert.toLong(pid));
             recommendUser.setToUserId(Userthread.getUser().getId());
             recommendUser.setScore(RandomUtil.randomDouble(60, 90));
             recommendUsers.add(recommendUser);
         }
        }
        for (RecommendUser recommendUser : recommendUsers) {
            UserInfo userInfo = userInfoApi.getUserInfo(recommendUser.getUserId());
            TodayBest todayBest = TodayBest.init(userInfo, recommendUser);
            list.add(todayBest);
        }
        return list;
    }

    public void likeUser(Long likeUserId) {
        Long userId = Userthread.getUser().getId();
        likeUserApi.likeUser(userId,likeUserId);
       Boolean isMember = redisTemplate.opsForSet().isMember(Constants.USER_NOT_LIKE_SET_KEY+userId,likeUserId.toString());
       if(isMember){
           redisTemplate.opsForSet().remove(Constants.USER_NOT_LIKE_SET_KEY+userId,likeUserId.toString());
       }
       redisTemplate.opsForSet().add(Constants.USER_LIKE_SET_KEY+userId,likeUserId.toString());
    Boolean likeUsereacher =   likeUserApi.likeUsereacher(likeUserId,userId);
    if(likeUsereacher){
        friendApi.saveFriend(userId,likeUserId);
        huanXinTemplate.addContact(Constants.HX_USER_PREFIX+userId,Constants.HX_USER_PREFIX+likeUserId);
    }

    }

    public void notLikeUser(Long unlikeUserId) {
        Long userId = Userthread.getUser().getId();
        likeUserApi.unlikeUser(userId,unlikeUserId);
        Boolean isMember = redisTemplate.opsForSet().isMember(Constants.USER_LIKE_SET_KEY+userId,unlikeUserId.toString());
        if(isMember){
            redisTemplate.opsForSet().remove(Constants.USER_LIKE_SET_KEY+userId,unlikeUserId.toString());
        }
        redisTemplate.opsForSet().add(Constants.USER_NOT_LIKE_SET_KEY+userId,unlikeUserId.toString());
    }

    public List<NearUserVo> searchUser(String gender, String distance) {
        Long userId = Userthread.getUser().getId();
      List<Long> userIds = userLocationApi.serchUser(userId,distance);
      List<NearUserVo> list = new ArrayList<>();
      if(CollUtil.isEmpty(userIds)){
          return new ArrayList<>();
      }
      for (Long userId1 : userIds) {
          UserInfo userInfo = userInfoApi.getUserInfo(userId1);
          if(userInfo!=null&&gender.equals(userInfo.getGender())){
              NearUserVo nearUserVo = NearUserVo.init(userInfo);
              list.add(nearUserVo);
          }
      }
      return list;
    }
}
